<template>
    <view class="u-demo-block">
        <u-gap bgColor="transparent" height="15"></u-gap>
        <view class="flex_wrap row_right"
            ><view class="lookBox" @click="lookBtn">预览</view></view
        >
        <u-swiper
            :list="templates"
            @change="(e) => (currentNum = e.current)"
            :autoplay="false"
            previousMargin="1"
            nextMargin="1"
            keyName="image"
            height="550rpx"
            width="378rpx"
            imgMode="aspectFit"
            :current="currentNum"
        >
            <view slot="indicator">
                <view class="indicator-num"
                    ><text class="indicator-num__text"
                        >{{ currentNum + 1 }}/{{ templates.length }}</text
                    ></view
                >
                <view class="indicator"
                    ><view
                        class="indicator__dot"
                        v-for="(item, index) in templates"
                        :key="index"
                        :class="[
                            index === currentNum && 'indicator__dot--active',
                        ]"
                    >
                    </view
                ></view>
            </view>
        </u-swiper>
        <u-gap bgColor="transparent" height="15"></u-gap>
        <view style="flex: 1; overflow: scroll"
            ><view v-for="(item, i) in templates" :key="i">
                <view v-show="i === currentNum" class="fromBox">
                    <view class="flex_wrap row_between-column_center">
                        <u--text
                            :text="`文本编辑`"
                            color="#3D3D3D"
                            size="32rpx"
                            bold />
                        <u-icon
                            name="trash"
                            label="删除此页"
                            labelSize="26rpx"
                            bold
                            size="48rpx"
                            color="#F56C6C"
                            labelColor="#F56C6C"
                            @click="deletePage(i)"
                    /></view>
                    <view v-for="(v, e) in item.modules" :key="e">
                        <!-- 文本 field -->
                        <view v-if="['field'].includes(v.type)">
                            <view v-for="a in v.config.value">
                                <u--text
                                    :text="a.label"
                                    color="#3D3D3D"
                                    size="32rpx"
                                    bold
                                    :customStyle="{ padding: '30rpx 0' }" />
                                <u--input
                                    v-model="a.text"
                                    :placeholder="`请输入${a.label}`"
                                    fontSize="28rpx"
                                    clearable
                                    maxlength="30"
                                    :customStyle="customInputStyle"
                                ></u--input
                            ></view>
                        </view>
                        <!-- 文本 field -->
                        <view v-if="['timeline'].includes(v.type)">
                            <view v-for="(a, b) in v.config.value">
                                <view
                                    ><u--text
                                        :text="`会议时间${b + 1}`"
                                        color="#3D3D3D"
                                        size="32rpx"
                                        bold
                                        :customStyle="{ padding: '30rpx 0' }" />
                                    <u--input
                                        v-model="a.time"
                                        :placeholder="`请输入会议时间`"
                                        fontSize="28rpx"
                                        clearable
                                        maxlength="30"
                                        :customStyle="customInputStyle"
                                    ></u--input
                                ></view>
                                <view
                                    ><u--text
                                        :text="`会议流程${b + 1}`"
                                        color="#3D3D3D"
                                        size="32rpx"
                                        bold
                                        :customStyle="{ padding: '30rpx 0' }" />
                                    <u--input
                                        v-model="a.text"
                                        placeholder="请输入会议流程"
                                        fontSize="28rpx"
                                        clearable
                                        maxlength="30"
                                        :customStyle="customInputStyle"
                                    ></u--input
                                ></view>
                            </view>
                        </view>
                        <!-- 文本 text -->
                        <view v-if="['text'].includes(v.type)">
                            <u--text
                                :text="v.label"
                                color="#3D3D3D"
                                size="32rpx"
                                bold
                                :customStyle="{ padding: '30rpx 0' }" />
                            <u--input
                                v-model="v.config.value"
                                :placeholder="`请输入${v.label}`"
                                fontSize="28rpx"
                                clearable
                                maxlength="30"
                                :customStyle="customInputStyle"
                            ></u--input
                        ></view>
                        <!-- 地址 地图map -->
                        <view v-if="v.type === 'navigation'">
                            <u--text
                                :text="v.label"
                                color="#3D3D3D"
                                size="32rpx"
                                bold
                                :customStyle="{ padding: '30rpx 0' }" />
                            <view class="mapBox">
                                <u--text
                                    align="right"
                                    :lines="3"
                                    :iconStyle="iconStyle"
                                    color="#666"
                                    size="28rpx"
                                    suffixIcon="arrow-right"
                                    :text="
                                        v.config.value
                                            ? v.config.value
                                            : `${v.label}`
                                    "
                                    @click="getLocation(v)"
                                /> </view
                        ></view>
                        <!-- 多文字框 -->
                        <view v-if="v.type === 'textarea'">
                            <u--text
                                :text="v.label"
                                color="#3D3D3D"
                                size="32rpx"
                                bold
                                :customStyle="{ padding: '30rpx 0' }" />
                            <u-textarea
                                count
                                autoHeight
                                maxlength="1000"
                                inputAlign="right"
                                fontSize="28rpx"
                                clearable
                                :placeholder="`请输入${v.label}`"
                                :customStyle="customInputStyle"
                                v-model="v.config.value"
                        /></view>
                        <!-- 图片上传 -->
                        <view v-if="v.type === 'images'">
                            <u--text
                                :text="v.label"
                                color="#3D3D3D"
                                size="32rpx"
                                bold
                                :customStyle="{ padding: '30rpx 0' }" />
                            <u-upload
                                :fileList="v.config.value"
                                @afterRead="
                                    (event) => afterRead(event, v, i, e)
                                "
                                @delete="(event) => deletePic(event, v, i, e)"
                                :previewFullImage="true"
                                name="0"
                                multiple
                                :maxCount="6"
                                width="200rpx"
                                height="200rpx"
                                accept="image"
                                uploadIcon="plus"
                                :customStyle="{
                                    marginLeft: '20rpx',
                                    marginTop: '40rpx',
                                }"
                            ></u-upload
                        ></view>
                    </view>
                </view>
                <!-- <u-form-item
                    label="会议主题"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="theme"
                >
                    <u-input
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        maxlength="30"
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.theme"
                    />
                </u-form-item> -->
                <!-- <u-form-item
                    label="开始时间"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="startSubmitTime"
                >
                    <u-datetime-picker
                        :show="pickerShow"
                        mode="datetime"
                        v-model="model.startTime"
                        @confirm="startTimeChange"
                        @cancel="pickerShow = false"
                    ></u-datetime-picker>

                    <u-text
                        align="right"
                        :iconStyle="iconStyle"
                        @click="pickerShow = true"
                        color="#666"
                        size="28rpx"
                        suffixIcon="arrow-right"
                        :text="
                            model.startSubmitTime
                                ? model.startSubmitTime
                                : '请选择开始时间'
                        "
                    />
                </u-form-item>

                <u-form-item
                    label="结束时间"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="endSubmitTime"
                    :clearIcon="false"
                >
                    <u-datetime-picker
                        :show="pickerShow2"
                        mode="datetime"
                        v-model="model.endTime"
                        @confirm="endTimeChange"
                        @cancel="pickerShow2 = false"
                    ></u-datetime-picker>
                    <u-text
                        align="right"
                        :iconStyle="iconStyle"
                        color="#666"
                        size="28rpx"
                        suffixIcon="arrow-right"
                        @click="pickerShow2 = true"
                        :text="
                            model.endSubmitTime
                                ? model.endSubmitTime
                                : '请选择结束时间'
                        "
                    />
                </u-form-item>
                <u-form-item
                    label="地址"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="illegalPlace"
                >
                    <view style="width: 530rpx">
                        <u--text
                            align="right"
                            :lines="3"
                            :iconStyle="iconStyle"
                            color="#666"
                            size="28rpx"
                            suffixIcon="arrow-right"
                            :text="
                                model.illegalPlace
                                    ? model.illegalPlace
                                    : '请选择地址'
                            "
                            @click="getLocation"
                        />
                    </view>
                </u-form-item>
                <u-form-item
                    label="详细场地"
                    :customStyle="formItemCustomStyle"
                    borderBottom
                    prop="address"
                >
                    <u-textarea
                        inputAlign="right"
                        fontSize="28rpx"
                        clearable
                        placeholderClass="placeHolder"
                        :customStyle="customInputStyle"
                        v-model="model.address"
                    />
                </u-form-item> -->
            </view></view
        >
    </view>
</template>

<script>
import moment from "moment";
import { baseUrl } from "@/config/tendIdConfig.js";
import {
    invitationLetterInfo,
    businessInvitationLetter,
    getOfLetterTemplate,
    update,
} from "@/api/invitationCardMake";
let pageId = "";
let invitationLetterIdPage = "";
let letterName = "";
let meetId = "";
let editStatus = "";
export default {
    data() {
        return {
            currentNum: 0,
            templates: [],
            pickerShow: false,
            pickerShow2: false,
            loading: false,
            startPicker: "",
            confirmButtonCustomstyle: {
                border: "none",
                height: "52rpx",
            },
            buttonCustomStyle: {
                color: "#FFF",
                backgroundColor: "#588BF3",
                // marginTop: '80rpx'
            },
            indexSearchKeyword: "",
            indexedChoosed: {},
            indexListHeight: 0,
            searchHeight: uni.upx2px(84),
            labelStyle: {
                fontSize: "32rpx",
                color: "#3D3D3D",
            },

            customInputStyle: {
                backgroundColor: "#F7F7F7",
                borderRadius: "8rpx",
                border: "1rpx solid #E9E9E9",
            },
            iconStyle: "fontSize:28rpx",
            preChooseList: [],
        };
    },
    onLoad(o) {
        pageId = o.id;
        letterName = o.letterName;
        meetId = o.meetId;
        console.log("o :>> ", o);
        editStatus = o?.type ?? "";
        if (editStatus) {
            // 编辑
            getOfLetterTemplate(pageId).then((res) => {
                console.log("res :>> ", res);
                const {
                    code,
                    data: { config, invitationLetterId },
                } = res;
                if (code === 200 && config) {
                    const configJson = JSON.parse(config);
                    this.templates = configJson.templates;
                    invitationLetterIdPage = invitationLetterId;
                    console.log("config :>> ", configJson);
                }
            });
        } else {
            // 新建
            invitationLetterInfo(pageId).then((res) => {
                console.log("res :>> ", res);
                const {
                    code,
                    data: { config, id },
                } = res;
                if (code === 200 && config) {
                    const configJson = JSON.parse(config);
                    this.templates = configJson.templates;
                    invitationLetterIdPage = id;
                    console.log("config :>> ", configJson);
                }
            });
        }
    },
    methods: {
        async lookBtn() {
            console.log(
                "templatestemplatestemplatestemplates :>> ",
                this.templates.filter(
                    (item) => item.modules[0]["type"] === "timeline"
                )
            );
            const copyTemplates = JSON.parse(JSON.stringify(this.templates));
            // 处理 流程 有些是否填写数据处理
            for (let [key, val] of copyTemplates.entries()) {
                if (val.modules[0]["type"] === "timeline") {
                    const valueList = val.modules[0]["config"]["value"];
                    // console.log(valueList.filter((e) => e.text || e.time));
                    val.modules[0]["config"]["value"] = valueList.filter(
                        (e) => e.text || e.time
                    );
                }
            }

            const params = editStatus
                ? {
                      config: JSON.stringify({ templates: copyTemplates }),
                      id: pageId,
                      isPreview: 1,
                  }
                : {
                      invitationLetterId: invitationLetterIdPage,
                      letterName,
                      status: 3,
                      isPreview: 1,
                      config: JSON.stringify({ templates: copyTemplates }),
                      meetId,
                  };
            console.log(
                "objetemplatestemplatestemplatesct :>> ",
                this.templates
            );
            let { data, code } = editStatus
                ? await update(params)
                : await businessInvitationLetter(params);
            if (code === 200) {
                data = editStatus ? pageId : data;
                uni.$u.route({
                    url: `/pages_swiper/index/index?id=${data}&isPreview=1&type=${editStatus}`,
                });
            }
        },

        async afterRead(event, v, i, o) {
            console.log(event, "vvvvvvv :>> ", v.config.value);
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            const arrayList =
                v.config.value === "" ? [] : [].concat(v.config.value);
            let fileListLen = arrayList.length;
            lists.map((item) => {
                arrayList.push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url);
                let item = arrayList[fileListLen];
                arrayList.splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        uploadResult: result,
                        url: result,
                    })
                );
                fileListLen++;
            }

            console.log(this.templates[i]["modules"][o].config.value);
            this.templates[i]["modules"][o].config.value = arrayList;
        },
        deletePic(event, v, i, o) {
            this.templates[i]["modules"][o].config.value.splice(event.index, 1);
        },
        deletePage(i) {
            if (this.templates.length === 1)
                return uni.$u.toast("无法删除模板页面！");
            if (this.templates.length - 1 == i) this.currentNum = i - 1;
            this.templates.splice(i, 1);
        },
        async uploadFilePromise(url) {
            const that = this;
            return new Promise((resolve, reject) => {
                const token = uni.getStorageSync("access_token");
                let a = uni.uploadFile({
                    url: `${baseUrl}/salesman/fileOss/uploadFileImg`,
                    filePath: url,
                    header: {
                        "Content-Type": "multipart/form-data",
                        Authorization: `Bearer ${token}` || "",
                    },
                    name: "file",
                    success: (res) => {
                        const result = JSON.parse(res.data);
                        if (result.code === 200) {
                            uni.showToast({
                                title: "上传成功",
                                icon: "success",
                            });
                            setTimeout(() => {
                                resolve(result.data);
                            }, 1000);
                        } else {
                            uni.showToast({
                                title: "上传失败",
                                icon: "fail",
                            });
                            setTimeout(() => {
                                reject(result.msg);
                            }, 1000);
                        }
                    },
                });
            });
        },
        formatAddress(str) {
            const reg = new RegExp(
                "(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+?(区{1})|.+市|.+旗|.+海域|.+岛)?(?<village>.*)"
            );
            if (!str) return; // 中国4个直辖市
            const municipality = ["重庆", "北京", "上海", "天津"];
            const subStr = str.substring(0, 2);
            const isExist = municipality.includes(subStr);
            if (isExist) {
                str = str.substring(2, str.length - 1);
                str = `${subStr}省${str}`;
            }
            let addr = str.match(reg);
            if (!addr) return;
            const groups = Object.assign({}, addr.groups); // 如果是直辖市，截取地址后，把省字替换成市
            if (isExist) {
                groups.province = groups.province.replace("省", "市");
            }
            return {
                ...groups,
                isExist: isExist, // 是否为直辖市
            };
        },
        getLocation(v) {
            const that = this;
            uni.chooseLocation({
                success: function (res) {
                    const addressGroups = that.formatAddress(res.address);
                    // 经纬度
                    v.config.longitude = res.longitude;
                    v.config.latitude = res.latitude;
                    v.config.value = `${res.address}(${res.name})`;
                    v.config.address = res.address;
                    console.log(res, "object :>> ", addressGroups);
                },
                fail(locationResult) {
                    if (
                        locationResult.errMsg ===
                        "chooseLocation:fail auth deny"
                    ) {
                        uni.showModal({
                            title: "提示",
                            content: "填写违法地点需要获取您的定位权限",
                            success(modalResult) {
                                const { confirm } = modalResult;

                                if (confirm) {
                                    uni.openSetting({
                                        success(openSettingResult) {
                                            if (
                                                openSettingResult.authSetting[
                                                    "scope.userLocation"
                                                ] === true
                                            ) {
                                                that.getLocation(v);
                                            } else {
                                                uni.showToast({
                                                    title: "获取授权失败",
                                                    icon: "none",
                                                    duration: 2000,
                                                });
                                            }
                                        },
                                    });
                                }
                            },
                        });
                    }
                },
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.u-demo-block {
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.indicator {
    @include flex(row);
    justify-content: center;
    position: fixed;
    top: 48%;
    left: 39%;
    &__dot {
        height: 6px;
        width: 6px;
        border-radius: 100px;
        background-color: #000;
        margin: 0 5px;
        transition: background-color 0.3s;

        &--active {
            background-color: #588bf3;
        }
    }
}

.indicator-num {
    height: 60rpx;
    background-color: rgba(97, 97, 97, 0.5);
    border-radius: 100px;
    width: 112rpx;
    @include flex;
    justify-content: center;
    position: fixed;
    top: 30rpx;
    left: 43%;
    align-items: center;
    &__text {
        color: #ffffff;
        font-size: 28rpx;
    }
}
.fromBox {
    background-color: #fff;
    padding: 32rpx;
}
.lookBox {
    background: #588bf3;
    font-size: 32rpx;
    color: #fff;
    width: 128rpx;
    height: 60rpx;
    border-radius: 50rpx;
    line-height: 60rpx;
    text-align: center;
    margin-right: 30rpx;
    margin-bottom: 16rpx;
}
.mapBox {
    background-color: #f7f7f7;
    height: 40px;
    border-radius: 4px;
    border: 1px solid #e9e9e9;
    display: flex;
    padding-right: 20rpx;
}
</style>
